package com.clwl.supervise.superviseapp.service.inspect;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.JgProcessCode;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.risk.JgPointDistance;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.JgProcessCodeMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.risk.JgRiskCheckContentMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.service.base.BaseDataService;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service
public class SpecialInspectService {


    @Resource
    private JgUnplannedCompanyMapper jgUnplannedCompanyMapper;

    @Resource
    private BaseDataService baseDataService;


    @Resource
    private JgProcessCodeMapper jgProcessCodeMapper;


    @Resource
    private JgClassifySpxsMapper classifySpxsMapper;


    @Resource
    private JgClassifyCyfwMapper classifyCyfwMapper;


    @Resource
    private JgCheckContentMapper jgCheckContentMapper;

    @Resource
    private JgTemplateMapper templateMapper;

    @Resource
    private JgClassifySpscCompMapper classifySpscCompMapper;

    @Resource
    private JgDailyCheckMapper jgDailyCheckMapper;

    @Resource
    private JgDailyCheckSetMapper   jgDailyCheckSetMapper;
    @Resource
    private JgClassifySpscCompMapper   jgClassifySpscCompMapper;

    @Resource
    private JgStandardMapper jgStandardMapper;

    @Resource
    private JgDailyStandardMapper jgDailyStandardMapper;

    @Resource
    private JgDailyContentMapper jgDailyContentMapper;

    @Resource
    private JsEntAnomalyMapper jsEntAnomalyMapper;

    @Resource
    private JgCheckGuideMapper checkGuideMapper;


    @Resource
    private JgRectificationMapper rectificationMapper;

    @Resource
    private JgRectificationContentMapper  rectificationContentMapper;

    @Resource
    private JgInvestigationMapper  investigationMapper;
    @Resource
    private JgInvestigationSetMapper  investigationSetMapper;

    @Resource
    private JgInvestigationContentMapper  investigationContentMapper;


    @Resource
    private JgScDynamicScoringMapper  scDynamicScoringMapper;


    @Resource
    private TcCompanyMapper companyMapper;

    @Resource
    private JgRiskCheckContentMapper riskCheckContentMapper;


    /**
     * 专项检查
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectCompanyPage(Integer pageNum, Integer pageSize, CommonSearchEntity params) {
        params.setUserId(UserHelper.getUserId());
        params.setDataRange(UserHelper.getUserInfo().getDataRange());
        params.setDeptId(UserHelper.getUserInfo().getDeptId());

        List<String> processList = CompanyProcessUtil.getUserProcessList();
        params.setProcessList(processList);
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        if ("0".equals(params.getType())) {
           /* Long dataCount =  jgUnplannedCompanyMapper.selectInpectionCount(params);
            iPage.setTotal(dataCount);*/
            IPage<Map<String, Object>> pageList = jgUnplannedCompanyMapper.selectInpectionPage(iPage,params);
            for (Map<String, Object> record : pageList.getRecords()) {
                //本年应该检查的次数
                String checkIds = record.get("CHECK_ID") == null ? "" : record.get("CHECK_ID") + "";
                String unplannedCompanyId = record.get("UNPLANNED_COMPANY_ID") == null ? "" : record.get("UNPLANNED_COMPANY_ID") + "";
                String checkIndexs = record.get("CHECK_INDEX") == null ? "0" : record.get("CHECK_INDEX") + "";
                String checkStatuss = record.get("CHECK_STATUS") == null ? "0" : record.get("CHECK_STATUS") + "";
                String[] checkIdArr = checkIds.split(",");
                String[] unplannedCompanyIdArr = unplannedCompanyId.split(",");
                String[] checkIndexArr = checkIndexs.split(",");
                String[] checkStatusArr = checkStatuss.split(",");
                List<Map<String,Object>> indexList = new ArrayList<>();
                for (int i = 0; i < checkIndexArr.length ; i++) {
                    Map<String,Object> checkMap = new HashMap<>();
                    checkMap.put("UNPLANNED_COMPANY_ID",unplannedCompanyIdArr[i]);
                    checkMap.put("CHECK_END_DATE",checkIndexArr[i]);
                    if("0".equals(checkIdArr[i])) {
                        checkMap.put("CHECK_ID", checkIdArr[i]);
                    }
                    checkMap.put("CHECK_STATUS",checkStatusArr[i]);
                    indexList.add(checkMap);
                }
                record.put("CHECK_LIST", indexList);
            }
            return pageList;
        } else {
            return jgUnplannedCompanyMapper.selectInspectionResultPage(iPage, params);
        }

    }

    /**
     * 获取检查的时候基础信息
     * @param unplannedCompanyId JG_UNPLANNED_COMPANY表ID
     * @return
     */
    public JgDailyCheck getSpecialCheckInfo(Long unplannedCompanyId) {
        JgUnplannedCompany unplannedCompany = jgUnplannedCompanyMapper.selectById(unplannedCompanyId);
        TcCompany company = companyMapper.selectById(unplannedCompany.getCompanyId());
        synchronized ((unplannedCompanyId+"").intern()) {
            JgDailyCheck dailyCheck = jgUnplannedCompanyMapper.selectDailyCheckById(unplannedCompanyId);
            if (dailyCheck == null) {
                dailyCheck = new JgDailyCheck();
            }
            dailyCheck.setManageStatus(dailyCheck.getManageStatus() == null ? "0" : dailyCheck.getManageStatus());
            dailyCheck.setDelayCheck(dailyCheck.getDelayCheck() == null ? 0 : dailyCheck.getDelayCheck());
            dailyCheck.setVerificationRecords("");
            dailyCheck.setCompanyId(unplannedCompany.getCompanyId());
            dailyCheck.setSuperviseDeptName(company.getDeptName());
            dailyCheck.setLngLat(company.getLngLat());
            dailyCheck.setCompanyAddress(company.getAddress());
            JgPointDistance distance = baseDataService.getCheckDistance(dailyCheck.getCompanyId() + "");
            dailyCheck.setDistance(distance.getDistance());
            //获取企业的一级业态信息
            if (company.getSupProcess() != null) {
                JgProcessCode processCode = jgProcessCodeMapper.selectByCode(company.getSupProcess());
                dailyCheck.setCompanyTypeName(processCode.getName());
                switch (company.getSupProcess()) {
                    case "spxs":
                        JgClassifySpxs classifySpxs = classifySpxsMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                        dailyCheck.setCompanyTypeName(dailyCheck.getCompanyTypeName() + (classifySpxs == null ? "" : "/" + classifySpxs.getName()));
                        break;
                    case "cyfw":
                        JgClassifyCyfw classifyCyfw = classifyCyfwMapper.selectByProcessCodeAndCompanyType(processCode.getId(), company.getCompanyTypeId());
                        dailyCheck.setCompanyTypeName(dailyCheck.getCompanyTypeName() + (classifyCyfw == null ? "" : "/" + classifyCyfw.getName()));
                        break;
                    case "spsc":
                        Map<String, Object> classifysc = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "0");
                        dailyCheck.setCompanyTypeName(dailyCheck.getCompanyTypeName() + (classifysc == null ? "" : "/" + classifysc.get("NAME").toString()));
                        break;
                    case "tssc":
                        Map<String, Object> classifyts = classifySpscCompMapper.selectByCompanyId(company.getId(), processCode.getId(), "1", "1");
                        dailyCheck.setCompanyTypeName(dailyCheck.getCompanyTypeName() + (classifyts == null ? "" : "/" + classifyts.get("NAME").toString()));
                        break;
                }
            }
            dailyCheck.setSupProcess(company.getSupProcess());
            dailyCheck.setCompanyNatureBusiness(company.getBusinessScope());
            dailyCheck.setCompanyContact(company.getContact());
            dailyCheck.setCompanyContactPhone(company.getContactPhone());
            if (!("spsc".equals(company.getSupProcess()) || "tssc".equals(company.getSupProcess())) && company.getCompanyTypeId() == null) {
                throw new RuntimeException("企业业态信息为空,无法获取检查内容!");
            }
            dailyCheck.setDeptName(company.getDeptName());
            if (dailyCheck.getId() == null) {
                //模板类型也用日常的
                JgTemplate template = templateMapper.selectBySupProcess(company.getSupProcess(), company.getCompanyTypeId(), "1");
                if (template == null) {
                    throw new RuntimeException("没有可用检查模板!");
                }
                dailyCheck.setTemplateId(template.getId());
                dailyCheck.setDeptId(UserHelper.getUserInfo().getDeptId());
                dailyCheck.setType("6");
                Long maxCheckNum = jgDailyCheckMapper.selectMaxCheckNum(company.getId(), DateUtil.format(new Date(), "yyyy"));
                QueryWrapper<JgDailyCheckSet> queryWrapper = new QueryWrapper();
                queryWrapper.eq("RISK_LEVEL", company.getRiskLevel());
                queryWrapper.eq("DELETE_FLAG", "0");
                queryWrapper.eq("SUP_PROCESS", company.getSupProcess());
                JgDailyCheckSet jgDailyCheckSet = null;
                if (StringUtils.equalsAny(company.getSupProcess(), "tssc")) {
                    //需要匹配业态
                    List<JgClassifySpscComp> classifySpscComps = jgClassifySpscCompMapper.selectEntityByCompanyId(company.getId());
                    List<Long> classcifyId = classifySpscComps.stream().map(JgClassifySpscComp::getClassifySpsc1Id).collect(Collectors.toList());
                    queryWrapper.in("REGULATORY_FORMATS", classcifyId);
                    List<JgDailyCheckSet> dailyCheckSetList = jgDailyCheckSetMapper.selectList(queryWrapper);
                    //比较出frequency检查频次最大的数据
                    jgDailyCheckSet = dailyCheckSetList.stream().max(Comparator.comparing(JgDailyCheckSet::getFrequency)).get();
                } else {
                    jgDailyCheckSet = jgDailyCheckSetMapper.selectOne(queryWrapper);
                }
                Long frequency = 0L;
                if (jgDailyCheckSet != null) {
                    frequency = jgDailyCheckSet.getFrequency();
                }
                if (maxCheckNum == null) {
                    maxCheckNum = 0L;
                }
                dailyCheck.setCheckNum(frequency >= maxCheckNum ? frequency + 1 : maxCheckNum + 1);
                dailyCheck.setCheckStat("3");
                dailyCheck.setCheckPerson1Id(UserHelper.getUserId());
                dailyCheck.setCheckPerson1Name(UserHelper.getUserInfo().getName());
                List<TsUser> selectSuperviseList = baseDataService.getSupervisePersonList();
                //排除checkPerson2Id
                JgDailyCheck finalDailyCheck = dailyCheck;
                selectSuperviseList = selectSuperviseList.stream().filter(user -> {
                    return user.getId() != finalDailyCheck.getCheckPerson1Id();
                }).collect(Collectors.toList());
                if (selectSuperviseList.size() > 0) {
                    dailyCheck.setCheckPerson2Id(selectSuperviseList.get(0).getId());
                    dailyCheck.setCheckPerson2Name(selectSuperviseList.get(0).getName());
                }
                dailyCheck.setCheckPerson2Id(0L);
                dailyCheck.setCheckPerson2Name("");
                dailyCheck.setCompanyId(company.getId());
                dailyCheck.setCompanyName(company.getCompanyName());
                dailyCheck.setCreditCode(company.getCreditCode());
                dailyCheck.setLicense(company.getLicense());
                dailyCheck.setIsUnplanned("1");
                dailyCheck.setIsTempUnplanned("0");
                dailyCheck.setCheckYear(0L);
                dailyCheck.setCreateTime(new Date());
                dailyCheck.setCreatorId(UserHelper.getUserId());
                dailyCheck.setCreator(UserHelper.getUserInfo().getName());
                dailyCheck.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                dailyCheck.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                dailyCheck.setDeleteFlag(0L);
                dailyCheck.setTemplateName(template.getName());
                dailyCheck.setUnplannedId(unplannedCompanyId);
                jgDailyCheckMapper.insert(dailyCheck);
            } else {
                dailyCheck.setCheckPerson1Id(UserHelper.getUserId());
                dailyCheck.setCheckPerson1Name(UserHelper.getUserInfo().getName());
                jgDailyCheckMapper.updateById(dailyCheck);
            }
            String supProcess = company.getSupProcess();
            //查看当前企业是否之前填写了检查信息
            try {
                //获取已经填写的检查内容
                Map<String, String> riskMap = baseDataService.riskInfo(company.getId());
                List<String> riskCode = new ArrayList<>();
                Set<String> riskKeySet = riskMap.keySet();
                for (String riskKey : riskKeySet) {
                    if (!"0".equals(riskMap.get(riskKey))) {
                        riskCode.add(riskKey);
                    }
                }
                //标准列表
                List<JgStandard> checkStandardList = jgStandardMapper.selectStandardEntityList(supProcess, company.getCompanyTypeId());
                ArrayList<JgDailyStandard> dailyStandardList = new ArrayList<>();
                for (JgStandard standard : checkStandardList) {
                    JgDailyStandard dailyStandard = null;
                    if(dailyCheck.getId() != null) {
                        dailyStandard = jgDailyStandardMapper.selectStandard(standard.getId(),dailyCheck.getId());
                    }
                    if (dailyStandard == null) {
                        dailyStandard = new JgDailyStandard();
                        dailyStandard.setDailyCheckId(dailyCheck.getId());
                        dailyStandard.setCreateTime(new Date());
                        dailyStandard.setCreatorId(UserHelper.getUserId());
                        dailyStandard.setCreator(UserHelper.getUserInfo().getName());
                        dailyStandard.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                        dailyStandard.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                        dailyStandard.setDeleteFlag(0L);
                        dailyStandard.setTemplateId(standard.getTemplateId());
                        dailyStandard.setStandardId(standard.getId());
                        dailyStandard.setSupCategory(standard.getSupCategory());
                        dailyStandard.setSupProcess(standard.getSupProcess());
                        dailyStandard.setSpxsId(standard.getSpxsId());
                        dailyStandard.setCyfwId(standard.getCyfwId());
                        dailyStandard.setSpscLbId(standard.getSpscLbId());
                        dailyStandard.setSpscLbZlId(standard.getSpscLbZlId());
                        dailyStandard.setTsspLbId(standard.getTsspLbId());
                        dailyStandard.setTsspLbZlId(standard.getTsspLbZlId());
                        dailyStandard.setName(standard.getName());
                        dailyStandard.setSerialNum(standard.getSerialNum());
                        jgDailyStandardMapper.insert(dailyStandard);
                    }
    //                List<JgSchemeContent>  realySchemeContentList = schemeContentMapper.selectByStandardId(schemeStandard.getId());
                    List<JgCheckContent> checkContentList = jgCheckContentMapper.selectEntityByStandardId(standard.getId());
                    List<JgDailyContent>  schemeContentList = new ArrayList<>();
                    for (JgCheckContent jgCheckContent : checkContentList) {
                        JgDailyContent dailyContent = jgDailyContentMapper.selectByContentAndDailyStandard(jgCheckContent.getId(),dailyStandard.getId(),riskCode);
                        if(dailyContent == null) {
                            dailyContent = new JgDailyContent();
                            dailyContent.setContentId(jgCheckContent.getId());
                            dailyContent.setDailyStandardId(dailyStandard.getId());
                            dailyContent.setCheckContent(jgCheckContent.getCheckContent());
                            dailyContent.setImportentItem(jgCheckContent.getImportentItem());
                            dailyContent.setMissingItem(jgCheckContent.getMissingItem());
                            dailyContent.setRemark(jgCheckContent.getRemark());
                            dailyContent.setScore(jgCheckContent.getScore());
                            dailyContent.setSerialNum(jgCheckContent.getSerialNum());
                            dailyContent.setCreateTime(new Date());
                            dailyContent.setCreatorId(UserHelper.getUserId());
                            dailyContent.setCreator(UserHelper.getUserInfo().getName());
                            dailyContent.setCreateDeptId(UserHelper.getUserInfo().getDeptId());
                            dailyContent.setCreateDeptName(UserHelper.getUserInfo().getDeptName());
                            dailyContent.setDeleteFlag(0L);
                            try {
                                int  riskCount = riskCheckContentMapper.selectCountByCheckContent(jgCheckContent.getId(),riskCode);
                                dailyContent.setRiskCount(riskCount);
                            } catch (Exception e) {
                                dailyContent.setRiskCount(0);
                            }
                            JgCheckGuide checkGuide = checkGuideMapper.selectByContentId(jgCheckContent.getId());
                            if (checkGuide != null) {
                                dailyContent.setCheckBasis(checkGuide.getCheckBasis());
                                dailyContent.setCheckMethod(checkGuide.getCheckMethod());
                                dailyContent.setCheckGuide(checkGuide.getCheckGuide());
                                dailyContent.setCheckProblem(checkGuide.getCheckProblem());
                            }
                            //List<JgCheckMissing>  checkMissingList = checkMissingMapper.selectEntityByContentId(jgCheckContent.getId());
                            //dailyContent.setCheckMissingList(checkMissingList);
                            //List<JgCheckProblem>  checkProblemList = checkProblemMapper.selectEntityByContentId(jgCheckContent.getId());
                            //dailyContent.setCheckProblemList(checkProblemList);
                            jgDailyContentMapper.insert(dailyContent);
                        }
                        schemeContentList.add(dailyContent);
                    }
                    dailyStandard.setContentList(schemeContentList);
                    dailyStandardList.add(dailyStandard);
                }
                dailyCheck.setStandardList(dailyStandardList);

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("获取检查信息失败!");
            }

            return dailyCheck;

        }
    }

    /**
     * 保存临时保存检查内容
     * @param temporary
     * @param dailyCheck
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck saveCheckInfo( String temporary, JgDailyCheck dailyCheck) {
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());

        if ("2".equals(temporary)) {
            dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
            dailyCheck.setCheckStat("1");
        } else {
            dailyCheck.setCheckStat("3");
        }

        //保存检查内容列表信息
        saveItemListAndContentList(   dailyCheck);
        if ("1".equals(dailyCheck.getManageStatus())) {
            //如果选择的是异常的话
            dailyCheck.setProcessResults("2");
            //保存异常信息
            saveEntAnomaly( company, dailyCheck,  temporary);
        }
        jgDailyCheckMapper.updateById(dailyCheck);
        //这里只做临时保存了
        return dailyCheck;
    }

    /**
     * 保存检查内容
     * @param dailyCheck
     */
    @Transactional(rollbackFor = Exception.class)
    private void saveItemListAndContentList( JgDailyCheck dailyCheck) {
        List<JgDailyStandard> dailyStandardList = dailyCheck.getStandardList();
        for (JgDailyStandard dailyStandard : dailyStandardList) {
            jgDailyStandardMapper.updateById(dailyStandard);
            List<JgDailyContent> dailyContentList = dailyStandard.getContentList();
            for (JgDailyContent dailyContent : dailyContentList) {
                if(StringUtils.isNotBlank(dailyContent.getProblemFile()) && dailyContent.getProblemFile().indexOf("data:image") >= 0){
                    try {
                        FileResultEntity uploadEntity = FileUploadUtil.uploadImageBase64Image(dailyContent.getProblemFile(), FileUploadEnum.specialInspect.getPath());
                        dailyContent.setProblemFile(uploadEntity.getFilePath());
                    } catch (Exception e) {
                        throw new RuntimeException("文件存储失败");
                    }
                }
                JgCheckContent checkContent = jgCheckContentMapper.selectById(dailyContent.getContentId());
                if("1".equals(dailyContent.getSelection())){
                    dailyContent.setScore(checkContent.getYesScore());
                } else {
                    dailyContent.setScore(checkContent.getScore());
                }
                jgDailyContentMapper.updateById(dailyContent);
            }
        }
    }

    /**
     * 保存检查异常的信息
     * @param company 企业信息
     * @param dailyCheck 检查信息
     * @param temporary
     */
    @Transactional(rollbackFor = Exception.class)
    private void saveEntAnomaly(  TcCompany company,
                                JgDailyCheck dailyCheck,  String temporary) {
        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(),"4");
        if (jsEntAnomaly == null) {
            jsEntAnomaly = new JsEntAnomaly();
        }
        jsEntAnomaly.setCheckType("6");
        jsEntAnomaly.setCompanyId(company.getId());
        jsEntAnomaly.setCompanyName(company.getCompanyName());
        jsEntAnomaly.setCreditCode(company.getCreditCode());
        jsEntAnomaly.setLicense(company.getLicense());
        jsEntAnomaly.setDailyCheckId(dailyCheck.getId());
        jsEntAnomaly.setAbnormalCause(dailyCheck.getAbnormalCause());
        jsEntAnomaly.setAuditTrails(dailyCheck.getVerificationRecords());
        jsEntAnomaly.setRectifyTime(dailyCheck.getRectificationTimeLimit());
        jsEntAnomaly.setCheckResults(dailyCheck.getCheckResult());
        jsEntAnomaly.setProcessResults(dailyCheck.getProcessResults());
        if (!"2".equals(temporary)) {
            //临时存储的
            jsEntAnomaly.setDeleteFlag(2L);
        } else {
            //正式存储的
            jsEntAnomaly.setDeleteFlag(0L);
        }
        int checkNum = 0;
        //修改所有的检查内容为选择的否
        List<JgDailyStandard> dailyStandardList = dailyCheck.getStandardList();
        for (JgDailyStandard dailyStandard : dailyStandardList) {
            List<JgDailyContent> dailyContentList = dailyStandard.getContentList();
            for (JgDailyContent dailyContent : dailyContentList) {
                if(StringUtils.equals(dailyContent.getSelection(),"2")){
                    checkNum = checkNum + 1;
                }
                //dailyContent.setSelection("2");
                //dailyContentMapper.updateById(dailyContent);
            }
        }
        jsEntAnomaly.setCheckNumber(checkNum);
        if (jsEntAnomaly.getId() == null) {
            jsEntAnomaly.setCreateTime(new Date());
            jsEntAnomaly.setCreatorId(UserHelper.getUserId());
            jsEntAnomaly.setCreator(UserHelper.getUserInfo().getName());
            jsEntAnomalyMapper.insert(jsEntAnomaly);
        } else {
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }

    }



    /**
     * 最终保存
     *
     * @param checkId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JgDailyCheck finaSaveInfo(Long checkId) {
        JgDailyCheck dailyCheck = jgDailyCheckMapper.selectById(checkId);
        dailyCheck.setCheckStat("1");
        dailyCheck.setCheckTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        jgDailyCheckMapper.updateById(dailyCheck);
        TcCompany company = companyMapper.selectById(dailyCheck.getCompanyId());
        //如果选择的不是通过的话生成相应的后续步骤
        if ("2".equals(dailyCheck.getProcessResults())) {
            //责令整改
            saveRectification(dailyCheck.getRectificationTimeLimit(), company, dailyCheck);
        } else if ("3".equals(dailyCheck.getProcessResults())) {
            //选择调查处理同时也要生成一个整改信息
            saveRectification( dailyCheck.getRectificationTimeLimit(), company, dailyCheck);

                //调查处理,查看调查处理开关是否打开
                JgInvestigationSet investigationSet = investigationSetMapper.selectByCheckTypeAndProcess("6", company.getSupProcess());
                //调查处理开关打开的情况下才生成下面的内容
                if ("1".equals(investigationSet == null ? "2" : investigationSet.getCheckStatus())) {
                    saveInvestigation( company, dailyCheck);
                }
        }


        JsEntAnomaly jsEntAnomaly = jsEntAnomalyMapper.selectByCheckId(dailyCheck.getId(),"4");
        if (jsEntAnomaly != null) {
            jsEntAnomaly.setDeleteFlag(0L);
            jsEntAnomalyMapper.updateById(jsEntAnomaly);
        }

        //保存最新数据到评级的分数表，每年评级的时候要用
        List<JgDailyContent> dailyContentList = jgDailyContentMapper.selectEntityByDailyCheckId(checkId);
        for (JgDailyContent dailyContentMap : dailyContentList) {
            JgScDynamicScoring jgScDynamicScoring   = scDynamicScoringMapper.selectByContentIdAndCompanyId(dailyContentMap.getContentId(),dailyCheck.getCompanyId());
            if(jgScDynamicScoring == null) {
                jgScDynamicScoring = new JgScDynamicScoring();
                jgScDynamicScoring.setContentId(dailyContentMap.getContentId());
                jgScDynamicScoring.setCheckContent(dailyContentMap.getCheckContent());
                jgScDynamicScoring.setCompanyId(dailyCheck.getCompanyId());
                jgScDynamicScoring.setScore(dailyContentMap.getScore());
                jgScDynamicScoring.setSelection(dailyContentMap.getSelection());
                jgScDynamicScoring.setCreatorId(UserHelper.getUserId());
                jgScDynamicScoring.setCreatorName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setCreateTime(new Date());
                jgScDynamicScoring.setDeleteFlag("0");
                scDynamicScoringMapper.insert(jgScDynamicScoring);
            } else {
                jgScDynamicScoring.setUpdateTime(new Date());
                jgScDynamicScoring.setUpdateName(UserHelper.getUserInfo().getName());
                jgScDynamicScoring.setUpdateId(UserHelper.getUserId());
                scDynamicScoringMapper.updateById(jgScDynamicScoring);
            }
        }
        return dailyCheck;
    }

    /**
     * 保存整改信息
     *
     * @param rectificationTimeLimit 整改期限
     * @param company                企业信息
     * @param dailyCheck             日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public  void saveRectification(  String rectificationTimeLimit,
                                   TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgRectification> rectifications = rectificationMapper.selectByCheckId(dailyCheck.getId(), "6");
        JgRectification rectification;
        if (rectifications.size() > 0) {
            rectification = rectifications.get(0);
        } else {
            rectification = new JgRectification();
        }
        rectification.setCompanyId(company.getId());
        rectification.setCheckId(dailyCheck.getId());
        rectification.setCheckType("6");
        rectification.setCheckStatus("1");
        rectification.setRectificationTimeLimit(rectificationTimeLimit);
        rectification.setCreateTime(new Date());
        rectification.setCreatorId(UserHelper.getUserId());
        rectification.setCreatorName(UserHelper.getUserInfo().getName());
        rectification.setDeleteFlag(0L);
        if(rectification.getId() == null) {
            rectificationMapper.insert(rectification);
        } else {
            rectificationMapper.updateById(rectification);

        }

        //保存整改内容的初始信息
        List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
        for (JgDailyContent jgDailyContent : dailyContent) {
            JgRectificationContent rectificationContent = new JgRectificationContent();
            rectificationContent.setRectificationId(rectification.getId());
            rectificationContent.setCheckType("6");
            rectificationContent.setCheckContentId(jgDailyContent.getId());
            rectificationContent.setCreateTime(new Date());
            rectificationContent.setCreatorId(UserHelper.getUserId());
            rectificationContent.setCreatorName(UserHelper.getUserInfo().getName());
            rectificationContent.setDeleteFlag(0L);
            rectificationContent.setSerialNum(jgDailyContent.getStandardNum());
            rectificationContent.setStandardName(jgDailyContent.getStandardName());
            rectificationContent.setContentNum(jgDailyContent.getSerialNum());
            rectificationContent.setCheckContent(jgDailyContent.getCheckContent());
            rectificationContent.setSelection(jgDailyContent.getSelection());
            rectificationContent.setProblemContent(jgDailyContent.getProblemContent());
            rectificationContent.setProblemFile(jgDailyContent.getProblemFile());
            rectificationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
            rectificationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
            rectificationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
            rectificationContentMapper.insert(rectificationContent);
        }
    }


    /**
     * 保存调查处理
     *
     * @param company    企业信息
     * @param dailyCheck 日常检查信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public  void saveInvestigation(TcCompany company, JgDailyCheck dailyCheck) {
        //如果已经存在整改单信息说明之前保存完成了 属于流程操作错误问题不进行保存
        List<JgInvestigation> investigations = investigationMapper.selectByCheckId(dailyCheck.getId(), "6");
        JgInvestigation investigation;
        if (investigations.size() > 0) {
            investigation = investigations.get(0);
        } else {
            investigation = new JgInvestigation();
        }
        investigation.setCompanyId(company.getId());
        investigation.setCheckId(dailyCheck.getId());
        investigation.setCheckType("6");
        investigation.setCheckStatus("1");
        investigation.setCreateTime(new Date());
        investigation.setCreatorId(UserHelper.getUserId());
        investigation.setCreatorName(UserHelper.getUserInfo().getName());
        investigation.setDeleteFlag(0L);
        investigation.setCheckPersonnel(UserHelper.getUserId());//处理人员，谁检查的就是谁
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        if(investigation.getId() == null) {
            investigationMapper.insert(investigation);
        } else {
            investigationMapper.updateById(investigation);
        }
        //保存整改内容的初始信息
        List<JgDailyContent> dailyContent = jgDailyContentMapper.selectNoPassList(dailyCheck.getId());
        for (JgDailyContent jgDailyContent : dailyContent) {
            JgInvestigationContent investigationContent = new JgInvestigationContent();
            investigationContent.setInvestigationId(investigation.getId());
            investigationContent.setCheckType("6");
            investigationContent.setCheckContentId(jgDailyContent.getId());
            investigationContent.setCreateTime(new Date());
            investigationContent.setCreatorId(UserHelper.getUserId());
            investigationContent.setCreatorName(UserHelper.getUserInfo().getName());
            investigationContent.setDeleteFlag(0L);
            investigationContent.setSerialNum(jgDailyContent.getStandardNum());
            investigationContent.setStandardName(jgDailyContent.getStandardName());
            investigationContent.setContentNum(jgDailyContent.getSerialNum());
            investigationContent.setCheckContent(jgDailyContent.getCheckContent());
            investigationContent.setSelection(jgDailyContent.getSelection());
            investigationContent.setProblemContent(jgDailyContent.getProblemContent());
            investigationContent.setProblemFile(jgDailyContent.getProblemFile());
            investigationContent.setProblemContentInput(jgDailyContent.getProblemContentInput());
            investigationContent.setMissingItemContent(jgDailyContent.getMissingItemContent());
            investigationContent.setMissingItemContentInput(jgDailyContent.getMissingItemContentInput());
            investigationContentMapper.insert(investigationContent);
        }

    }
}
